package chapter10.section5;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

public class AccountTools {
    public static Map<String, Account> getAccountFromFile(String fn) throws IOException, NumberFormatException {
        Map<String, Account> accounts = new HashMap<String, Account>();
        BufferedReader in = new BufferedReader(new FileReader(fn));
        String info = null;//用来保存每次读入的文件内容
        while (true) {
            info = in.readLine();//每次读取文件一行
            if (info == null) {//若返回值为null，则表示已到文件尾
                break;
            }
            String[] s = info.split(",");//利用文件的内容分隔符分解此行
            Account a = new Account(s[0], s[1], Integer.parseInt(s[2]));
            accounts.put(a.getId(), a);
        }
        return accounts;
    }

    public static void writeAccountsToFile(String fn, Map<String, Account> accounts) throws IOException {
        try (FileWriter writer = new FileWriter(fn)) {
            for (Account account : accounts.values()) {
                writer.write(account.getId() + "," + account.getName() + "," + account.getBalance() + "\n");
            }
        }
    }

    public static void main(String[] args) throws IOException {
        // 创建测试账户数据
        Map<String, Account> testAccounts = new HashMap<>();
        testAccounts.put("001", new Account("001", "张三", 1000));
        testAccounts.put("002", new Account("002", "李四", 2000));
        testAccounts.put("003", new Account("003", "王五", 3000));

        try {
            // 写入测试数据
            writeAccountsToFile("account.dat", testAccounts);
            System.out.println("账户数据写入完成");

            // 读取并打印账户数据
            Map<String, Account> as = getAccountFromFile("account.dat");
            System.out.println("\n读取到的账户数据:");
            for (Account a : as.values()) {
                System.out.println(a);
            }
        } catch (NumberFormatException e) {
            e.printStackTrace();
        }
    }
}